using System.Text;

namespace TPXSDK.NET.Mission.Instruction;

internal class InstCircleSet : Tokenizer
{
    public InstCircleSet(TokenizerAdmin admin)
    {
        Admin = admin;
        KeyName = "circleset";
        KeyValue = (int)FlyCmdId.CMD_CIRCLESET;
        Usage = @"circleset [repeatNum] [radius] [targetBearing]";
        Description = @"Set circle control parameters";
    }

    public override bool Process()
    {
        var flyCmp = Admin?.Compiler; if (null == flyCmp) return false;
        var tokens = flyCmp.GetLineTokens();

        if (null == tokens || tokens.Count != 4)
        {
            flyCmp.ErrorMsg = $"{KeyName} Invalid Usage";
            return false;
        }
        var cmd = new FlyCmdItem
        {
            Id = (byte)KeyValue,
            LineNum = tokens[0].Row
        };


        tokens.RemoveAt(0);// Remove cmd Name

        if (tokens[0].Type == TokenType.NUMBER &&
            tokens[1].Type == TokenType.NUMBER &&
            tokens[2].Type == TokenType.NUMBER)
        {
            cmd.P1 = Convert.ToByte(tokens[0].Name);
            cmd.P2 = FlyUtils.ToInt16(tokens[1].Name);
            cmd.P3.U16Val = Convert.ToUInt16(tokens[2].Name);
            cmd.P4.U32Val = 0;
            flyCmp.CmdList.Add(cmd);

            return true;
        }

        flyCmp.ErrorMsg = $"{KeyName} Invalid param";
        return false;
    }

    public override void Reverse(FlyCmdItem cmd, StringBuilder sb)
    {
        var src = $"{KeyName} {cmd.P1} {cmd.P2} {cmd.P3.U16Val}";
        sb.AppendLine(src);
    }
}
